package com.atguigu.dga.ds.service.impl;

import com.alibaba.fastjson.JSON;
import com.atguigu.dga.ds.bean.TDsTaskDefinition;
import com.atguigu.dga.ds.mapper.TDsTaskDefinitionMapper;
import com.atguigu.dga.ds.service.TDsTaskDefinitionService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author atguigu
 * @since 2023-06-09
 */
@Service
public class TDsTaskDefinitionServiceImpl extends ServiceImpl<TDsTaskDefinitionMapper, TDsTaskDefinition> implements TDsTaskDefinitionService {

    /*
    查询到今天所有参加考评的表的任务定义
        79张表都要参加考评
            30张都是ods层表。一次性执行一个脚本，导入，没有任务定义信息
            只获取今天所有参加考评的表，且被调度的表的任务信息

       选择一：自己编写sql t_ds_task_definition join t_ds_task_instance
       选择二：不用join实现
                查询的所有字段都来自t_ds_task_definition
                只是判断t_ds_task_definition表中的某个任务在t_ds_task_instance出现过
                select * from t_ds_task_definition
                where name in ( tableNames ) and exists ( select 1 from  t_ds_task_instance t1 where t1.name = name and date(start_time) = assessDate )
     */
    @Override
    public List<TDsTaskDefinition> getAllTasks(String assessDate, Set<String> tableNames) {

        QueryWrapper<TDsTaskDefinition> queryWrapper = new QueryWrapper<TDsTaskDefinition>()
                .in("name", tableNames)
                .exists(" select 1 from  t_ds_task_instance t1 where t1.name = name and date(start_time) = '" + assessDate + "'");

        List<TDsTaskDefinition> definitions = list(queryWrapper);

        for (TDsTaskDefinition definition : definitions) {

            definition.setSql(parseSql(definition.getTaskParams()));

        }

        //解析 task_params 中的 rawScripts中sql赋值给 TDsTaskDefinition

        return definitions;
    }

    private String parseSql(String taskParams){
        //小写的sql脚本
        String rawScript = JSON.parseObject(taskParams).getString("rawScript").toLowerCase();

        /*
        获取截取的起始位置
        CTE写法：
            with xx as(),xx as()
            insert xxx;

            不用CTE：insert xxxx
         */
        int start = rawScript.indexOf("with");

        //没有with
        if (start == -1){
            start = rawScript.indexOf("insert");
        }

        /*
        获取截取的起始位置
            写：结束
                set a=1;
                innsert xxx;
                set a=2;
            不写：
                sql="
                    set a=1;
                    insert xxx
                "
         */
        int end = rawScript.indexOf(";", start);

        if (end == -1){
            end = rawScript.indexOf("\"", start);
        }
        return rawScript.substring(start,end);
    }


}
